<!-- 修改密码 -->
<template>
    <dy-dialog 
        :title="title"
        ref="dialog"
        @submitHandle="submitHandle"
        :loading="loading"
    >
        <el-form
            :label-position="labelPosition"
            label-width="100px"
            :model="form"
            ref="ruleFormRef"
            :rules="rules"
            style="max-width: 460px"
        >
            <el-form-item label="新密码" required prop="password">
                <el-input v-model="form.password" show-password clearable/>
            </el-form-item>
            <el-form-item label="确认密码" required prop="again">
                <el-input v-model="form.again" show-password clearable/>
            </el-form-item>
        </el-form>
    </dy-dialog>
</template>

<script setup>
import { reactive, toRefs, ref } from 'vue'
import { ElMessage } from 'element-plus'

let state = reactive({
    title: '',
    labelPosition: 'left',
    user_id: '',
    loading: false,
    form: {}
})
//数据
let { title, labelPosition, form, loading } = toRefs(state)

//弹框实例
let dialog = ref(null)
//form实例
const ruleFormRef = ref(null)
//规则
const validator = (rule, value, callback) => {
    if(!value){
        return callback(new Error('请再次输入新密码'))
    }
    if(value != state.form.password){
        return callback(new Error('两次密码不一致'))
    }
    return callback()
}
//表单验证规则
const rules = reactive({
    password: [
        { required: true, message: '请输入新密码', trigger: 'blur' }
    ],
    again: [
        { validator, trigger: 'blur' }
    ]
})

//打开弹框执行
let openFunction = (params) => {
    state.title = params.title
    state.user_id = params.userId
}

//提交
let submitHandle = () => {
    ruleFormRef?.value.validate(async (valid) => {
        if(!valid){
            return false
        }
        let params = {
            id: state.user_id,
            password: state.form.password
        }
        state.loading = true
        let res = await commonV.methods.changeaxiosdata('users', 'patch', params)
        if(res){
            ElMessage({
                message: '修改成功!',
                type: 'success'
            })
            dialog.value.handleClose()
        }
        state.loading = false
    })
}

defineExpose({ openFunction })
</script>

<style lang="scss" scoped>
    
</style>